#!/usr/bin/python
from PIL import ImageTk
from RFB import RFBClient
import Tkinter as TK
import threading, time, sys


if len(sys.argv) < 3:
    print "Need 3 arguments"
    print "Usage: %s <ip> <port>"%sys.argv[0]
    sys.exit(1)

def updateImage():
    if l.update < test.Updates:
        img = ImageTk.PhotoImage(test.image)
        l.configure(image=img)
        l.image = img
        l.update = test.Updates

def task():
    updateImage()
    root.after(33, task)

def MouseMove(e):
    global MouseMask
    x=e.x
    y=e.y
    if e.widget == c:
        x += c.x
        y += c.y
    test.pointerEvent(x,y, MouseMask)
    img = ImageTk.PhotoImage(test.cursor)
    c.configure(image=img)
    c.image = img
    c.place(x=(x-test.cursorPOS[0]), y=(y-test.cursorPOS[1]))
    c.x = x
    c.y = y

def MouseDown(e):
    m =  1<< (e.num -1)
    global MouseMask
    MouseMask+=m
    test.pointerEvent(c.x,c.y, buttonmask=MouseMask)

def MouseUp(e):
    x=e.x
    y=e.y
    if e.widget == c:
        x += c.x
        y += c.y
    m = 1<< (e.num -1)
    global MouseMask
    MouseMask-=m
    test.pointerEvent(c.x,c.y, buttonmask=MouseMask)

def KeyPress(e):
    updateImage(timeout=0)
    test.sendString(e.char)

class RFBThread(threading.Thread):
    def __init__(self, t):
        self.update = 0
        self.t = t
        threading.Thread.__init__(self)
    def run(self):
        while True:
            if self.t.Updates > self.update and self.t.Complete == True:
                self.t.imageUpdateRequest(inc=1)
                self.update = self.t.Updates
            self.t.update(timeout=1.0)

MouseMask=0
test = RFBClient(host=sys.argv[1], port=int(sys.argv[2]))
test.VNCstart()
t = time.time()
startTime = time.time()
c=0
last = 0
root = TK.Tk()
root.geometry("%dx%d"%(test.width, test.height))
test.imageUpdateRequest(inc=1)
test.update(timeout=1)
if test.image == False:
    print "No image"
    sys.exit(1)
img = ImageTk.PhotoImage(test.image)
l = TK.Label(root, image=img, cursor='tcross')
l.pack(side = "bottom", fill = "both", expand = "yes")
l.update = 0
cimg = ImageTk.PhotoImage(test.cursor)
c = TK.Label(l, image=cimg)
c.pack()
c.place(x=0, y=0)
root.after(1, task)
root.bind("<Motion>", MouseMove)
root.bind("<ButtonPress>", MouseDown)
root.bind("<ButtonRelease>", MouseUp)
root.bind("<Key>", KeyPress)
t = RFBThread(test)
t.setDaemon(True)
t.start()
root.mainloop()

